#!/bin/bash
# 贝壳OC智能应用中心部署脚本

echo "=== 贝壳OC智能应用中心部署脚本 ==="

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "请使用root权限运行此脚本"
    echo "使用方法: sudo bash deploy.sh"
    exit 1
fi

# 1. 检查并安装必要软件
echo "1. 检查系统环境..."

# 检查Nginx
if ! command -v nginx &> /dev/null; then
    echo "安装Nginx..."
    apt update
    apt install -y nginx
else
    echo "✓ Nginx已安装"
fi

# 检查Python3
if ! command -v python3 &> /dev/null; then
    echo "安装Python3..."
    apt install -y python3 python3-pip
else
    echo "✓ Python3已安装"
fi

# 2. 创建项目目录
echo "2. 创建项目目录..."
PROJECT_DIR="/var/www/aioc"
mkdir -p $PROJECT_DIR

# 3. 复制文件
echo "3. 复制项目文件..."
cp *.html $PROJECT_DIR/ 2>/dev/null || echo "请手动复制HTML文件到 $PROJECT_DIR/"
cp *.css $PROJECT_DIR/ 2>/dev/null || echo "请手动复制CSS文件到 $PROJECT_DIR/"
cp *.js $PROJECT_DIR/ 2>/dev/null || echo "请手动复制JS文件到 $PROJECT_DIR/"
cp app.py $PROJECT_DIR/
cp requirements.txt $PROJECT_DIR/

# 4. 安装Python依赖
echo "4. 安装Python依赖..."
cd $PROJECT_DIR
pip3 install -r requirements.txt

# 5. 配置Nginx
echo "5. 配置Nginx..."
cp /path/to/your/project/aioc.conf /etc/nginx/sites-available/aioc.conf
ln -sf /etc/nginx/sites-available/aioc.conf /etc/nginx/sites-enabled/aioc.conf

# 删除默认配置（可选）
rm -f /etc/nginx/sites-enabled/default

# 测试Nginx配置
echo "6. 测试Nginx配置..."
nginx -t

if [ $? -eq 0 ]; then
    echo "✓ Nginx配置测试通过"
    
    # 重启Nginx
    echo "7. 重启Nginx..."
    systemctl restart nginx
    systemctl enable nginx
    
    echo "✓ Nginx已重启并设置为开机自启"
else
    echo "❌ Nginx配置测试失败，请检查配置文件"
    exit 1
fi

# 8. 启动Python后端
echo "8. 启动Python后端..."
cd $PROJECT_DIR

# 创建systemd服务文件
cat > /etc/systemd/system/aioc-backend.service << EOF
[Unit]
Description=AIOC Backend Service
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=$PROJECT_DIR
Environment=FLASK_ENV=production
ExecStart=/usr/bin/python3 app.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# 启动服务
systemctl daemon-reload
systemctl start aioc-backend
systemctl enable aioc-backend

echo "9. 检查服务状态..."
sleep 3

# 检查Python后端
if systemctl is-active --quiet aioc-backend; then
    echo "✓ Python后端服务运行正常"
else
    echo "❌ Python后端服务启动失败"
    systemctl status aioc-backend
fi

# 检查Nginx
if systemctl is-active --quiet nginx; then
    echo "✓ Nginx服务运行正常"
else
    echo "❌ Nginx服务异常"
    systemctl status nginx
fi

# 10. 测试API连接
echo "10. 测试API连接..."
sleep 2

# 测试后端健康检查
if curl -s http://127.0.0.1:3000/health > /dev/null; then
    echo "✓ 后端健康检查通过"
else
    echo "❌ 后端健康检查失败"
fi

# 测试Nginx代理
if curl -s http://localhost/health > /dev/null; then
    echo "✓ Nginx代理测试通过"
else
    echo "❌ Nginx代理测试失败"
fi

echo ""
echo "=== 部署完成 ==="
echo "项目目录: $PROJECT_DIR"
echo "访问地址: http://aioc.ke.com"
echo "API测试: http://aioc.ke.com/health"
echo ""
echo "如果遇到问题，请检查："
echo "1. 防火墙设置: ufw allow 80"
echo "2. 域名解析是否正确"
echo "3. 查看日志: tail -f /var/log/nginx/aioc_error.log"
echo "4. 查看后端日志: journalctl -u aioc-backend -f"